package com.xul.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xul.srb.core.listener.ExcelDictDtoListener;
import com.xul.srb.core.mapper.DictMapper;
import com.xul.srb.core.pojo.dto.ExcelDictDTO;
import com.xul.srb.core.pojo.entity.Dict;
import com.xul.srb.core.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author xul
 * @since 2021-11-06
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 数据字典上传文件
     *
     * @param inputStream
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDtoListener(baseMapper)).sheet().doRead();
        log.info("Excel导入成功");
    }

    /**
     * 数据字典导出文件
     *
     * @return
     */
    @Override
    public List<ExcelDictDTO> listDictData() {
        List<Dict> dictList = baseMapper.selectList(null);
        ArrayList<ExcelDictDTO> excelDictDTOArrayList = new ArrayList<>(dictList.size());
        dictList.forEach(list -> {
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            BeanUtils.copyProperties(list, excelDictDTO);
            excelDictDTOArrayList.add(excelDictDTO);
        });
        return excelDictDTOArrayList;
    }

    /**
     * 根据上级id查询字节的数据
     *
     * @param parentId
     * @return
     */
    @Override
    public List<Dict> listByParentId(Long parentId) {

        List<Dict> dictList = null;
        try {
            dictList = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList:" + parentId);
            // 先查询redis中是否存在数据列表
            if (dictList != null) {
                // 如果redis有数据就从redis中获取
                log.info("从redis中取值");
                return dictList;
            }
        } catch (Exception e) {
            log.error("redis的服务器异常：" + ExceptionUtils.getStackTrace(e));
        }

        log.info("从数据库中取值");
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        dictList = baseMapper.selectList(wrapper);
        dictList.forEach(list -> {
            Boolean hasChildren = hasChildren(list.getId());
            list.setHasChildren(hasChildren);
        });

        try {
            // 把数据存入到redis
            redisTemplate.opsForValue().set("srb:core:dictList:" + parentId, dictList, 5, TimeUnit.MINUTES);
            log.info("数据存入到redis");
        } catch (Exception e) {
            log.error("redis服务器异常：" + ExceptionUtils.getStackTrace(e));
        }

        return dictList;
    }

    /**
     * 根据dictCode获取到下级列表
     *
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return this.listByParentId(dict.getId());
    }

    /**
     * 根据value和dictCode在数据字典中获取名称
     *
     * @param value
     * @param dictCode
     * @return
     */
    @Override
    public String getNameByDictCodeAndValue(Integer value, String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        if (dict == null) {
            return "";
        }
        wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", dict.getId()).eq("value", value);
        dict = baseMapper.selectOne(wrapper);
        if (dict == null) {
            return "";
        }
        return dict.getName();
    }

    /**
     * 判断是否有子节点
     *
     * @param id
     * @return
     */
    private Boolean hasChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        if (count.intValue() > 0) {
            return true;
        } else {
            return false;
        }
    }
}
